<?php
// +----------------------------------------------------------------------
// | TYCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: aliang <461321026@qq.com>
// +----------------------------------------------------------------------
namespace app\home\controller;

use think\Db;

class Order extends Base
{
    protected $groupid = 0;
    protected function _initialize()
    {
        parent::_initialize();
        $hid = session('hid');
        $this->groupid = 0;
        if(!empty($hid)){
            $member  = session('user') ? session('user'):Db::name('member_list')->get($hid);
            $this->groupid = isset($member['member_list_groupid']) ? $member['member_list_groupid']:0;
        }
        $this->assign('groupid',$this->groupid);
   
    }
    
    public function index()
    {
		return $this->view->fetch();
    }
    
    public function buy(){
        $good_id = input("id",0,"intval");
        $number = input("number",1,"intval");
        $ids = input("ids");
        if($good_id<=0 && empty($ids)){
            $this->error(lang('operation not valid'));
        }
        
        $user = session('user');
        if(empty($user)) 
            $this->error('请登录用户再购买！',url('home/login/index').'?reffer='.url('home/shop/show',['id'=>$good_id]));
        $user = Db::name("member_list")->find(session('hid'));

        $where = [];
        $total = 0;
        if($good_id>0){
            $where["g.id"] = $good_id;
            $good = Db::name('goods')->alias("g")
                ->join("__GOODS_CATE__ gc","gc.gid = g.id","LEFT")
                ->join("__CATEGORY__ c","c.id = gc.cid","LEFT")
                ->join("__GOODS_PRICE__ gp","gp.gid = g.id","LEFT")
                ->where($where)
                ->field("g.*,gp.price_1,gp.price_2,gp.price_3,c.cate_name")->find();
            $good["currprice"] = $this->groupid>0 ? $good["price_".$this->groupid]:$good["price"];
            $good["totalprice"]= $total = $good["currprice"]*$number;
            $good["number"]    = $number;
            $youhui            = ($good["price"]*$number) - $good["totalprice"] ;
            $good['youhui']    = $youhui > 0 ? $youhui:'-';
            $goods[] = $good;
            
        }elseif(!empty($ids)){
            $where["g.id"] = ["in",$ids];
            $goods = Db::name('goods')->alias("g")
                ->join("__GOODS_CATE__ gc","gc.gid = g.id","LEFT")
                ->join("__CATEGORY__ c","c.id = gc.cid","LEFT")
                ->join("__GOODS_PRICE__ gp","gp.gid = g.id","LEFT")
                ->where($where)
                ->field("g.*,gp.price_1,gp.price_2,gp.price_3,c.cate_name")->select();
            foreach($goods as $key => $g){
                $g["currprice"] = $this->groupid>0 ? $g["price_".$this->groupid]:$g["price"];
                $g["totalprice"]= $g["currprice"]*$number;
                $total +=$g["totalprice"];
                $g["number"]= $number;
                
                $youhui            = ($g["price"]*$number) - $g["totalprice"] ;
                $g['youhui']       = $youhui > 0 ? $youhui:'-';

                $goods[$key] = $g;
            }
        }
        
        //支付方式获取
        $pament_list = config('payment');
        $brower      = x_get_browser();
        $paylist     = [];
         
        foreach($pament_list as $k=>$v){
           switch($brower){
               case 2:
                   if($k == 'wxpayqrcode'/*wxpaypub*/ ){
                       $v['code'] = $k;
                       $paylist[] = $v;
                   }
               break;
               
               case 1:
                   if($k=='aliwappay' || $k == 'wxpaypub'){
                       $v['code'] = $k;
                       $paylist[] = $v;
                   }
               break;
               
               default:
                   if(isset($v['display']) && $v['display'] == 1){
                       $v['code'] = $k;
                       $paylist[] = $v;
                   }
               break;
           }
        }
        
        $this->assign("brower",$brower);
        $user_money = isset($user['money']) ? (empty($user['money']) ? 0:$user['money']):0;
        $this->assign("user_money",$user_money);
        $this->assign("paylist",$paylist);
    
        //收货地址
        $address = Db::name('member_address')->where(["uid"=>session('hid')])->select();
        $this->assign("goods",$goods);
        $this->assign("address",$address);
        $this->assign("total",$total);
        return $this->view->fetch();
    }
    
    public function getprice(){
        $good_id = input("id",0,"intval");
        if($good_id<=0){
            return json(["err"=>1,"msg"=>"参数不正确！"]);
        }
        $number = input("number",1,"intval");
        $where["g.id"] = $good_id;
        $good = Db::name('goods')->alias("g")
            ->join("__GOODS_PRICE__ gp","gp.gid = g.id","LEFT")
            ->where($where)
            ->field("g.*,gp.price_1,gp.price_2,gp.price_3")->find();
        if(empty($good)){
            return json(["err"=>1,"msg"=>"商品不存在！"]);
        }else{
            $good["currprice"] = $this->groupid>0 ? $good["price_".$this->groupid]:$good["price"];
            $good["number"]    = $number;
            $good["totalprice"]= $good["currprice"]*$good["number"];
            
            $youhui            = ($good["price"]*$number) - $good["totalprice"] ;
            $good['youhui']    = $youhui > 0 ? $youhui:'-';
            
            return json(["err"=>0,"msg"=>"获取成功！","data"=>$good]);
        }
    }
    
    public function confirmorder(){
        $param = input();
        if(empty($param["address_id"]) || empty($param["id"]) || empty($param["number"])){
           $this->error(lang('operation not valid'));
        }
        $data = [];
        foreach($param["id"] as $key => $g){
            $good = Db::name('goods')->alias("g")
                ->join("__GOODS_PRICE__ gp","gp.gid = g.id","LEFT")
                ->where(["g.id"=>$g])
                ->field("g.*,gp.price_1,gp.price_2,gp.price_3")->find();
            if($good){
                $good["number"] = $param["number"][$key];
                $good["fee"] = $this->groupid>0 ? $good["price_".$this->groupid]:$good["price"];
                $good["total_fee"]= $good["fee"]*$good["number"];
                $good["address_id"] = intval($param["address_id"]);
                $good["address"] = Db::name("member_address")->where(["id"=>$good["address_id"]])->find();
                
                $pay_type  = isset($param['pay_type']) ? $param['pay_type']:'alipay';
                $user      = session('user');
                if(empty($user))
                    $this->error('请登录用户再购买！',url('home/login/index').'?reffer='.url('home/shop/show',['id'=>$g]));
                $user = Db::name("member_list")->find(session('hid'));
                if($user['money'] < $good['total_fee'] && $pay_type =='money')
                    $this->error('当前账户余额不足，请充值！',url('home/center/chongzhi'));

                $data[] = [
                    "subject"  => $good['goods_title'],
                    "pay_type" => $pay_type,
                    "sn" => date("Y").date("m").date('d').date("h").date("i").date("s").random(4,'number'),
                    "gid"=> $g,
                    "uid"=> session('hid'),
                    "number" => $good["number"] , 
                    "fee"    => $good["fee"],
                    "total_fee"=> $good["total_fee"],
                    "add_time" => time(),
                    "last_time"=> time(),
                    "address_id"=>intval($param["address_id"]),
                    "address_cache"=> empty($good["address"])? "":serialize($good["address"])
                ];
            }
        }
        if(count($data)>0){
            //预留多商品订单，但现在数据结构只支持一个商品
            $res = Db::name('goods_order')->insertGetid($data[0]);
            if($res){
                
                
                $content = "<p><b>商品名称:</b>{$data[0]['subject']}</p>".
                    "<p><b>商品数量:</b>{$data[0]["number"]}</p>".
                    "<p><b>订单总价:</b>{$data[0]["total_fee"]}</p>".
                    "<p><b>订单编号:</b>{$data[0]['sn']}</p>".
                    "<p><b>下单时间:</b>".date('Y-m-d H:i:s',time())."</p>";
                if($data[0]['address_id']>0){
                    $add_info = Db::name("member_address")->where("id",$data[0]['address_id'])->find();
                    if(!empty($add_info)){
                       $province = $add_info['province'] > 0 ? Db::name("Region")->where('id',$add_info['province'])->value('name'):''; 
                       $city     = $add_info['city']>0  ? Db::name("Region")->where('id',$add_info['city'])->value('name'):'';
                       $district = $add_info['district']>0  ? Db::name("Region")->where('id',$add_info['district'])->value('name'):'';
                       
                       if(!empty($add_info['man']))
                           $content .= "<p><b>收件姓名:</b>{$add_info['man']}</p>";
                       if(!empty($add_info['mobile']))
                           $content .= "<p><b>收件电话:</b>{$add_info['mobile']}</p>";
                       $st_address   = trim($province.$city.$district.$add_info['address']);
                       if(!empty($st_address))
                           $content .= "<p><b>收件地址:</b>{$st_address}</p>"; 
                    } 
                }
                
                $content .= "<br><p><b>请登录系统后台， 商品管理-->订单管理  查看最新订单信息 </b></p>";
                $send_result=sendMail(config("options.site_admin_email"),"新订单提醒:订单编号". $data[0]['sn'], $content);
                
                
                
                //$this->success("恭喜，订单创建成功！",url("home/order/index"));
                $this->redirect(url("home/payment/payorder",['id'=>$res])); //创建订单成功，跳转到付款页面
            }else{
                $this->error("抱歉，订单创建失败！");
            }
        }else{
            $this->error("抱歉，订单信息缺失！");
        }
    }
    
    //详细页
    public function show(){
        $good_id = input("id",0,"intval");
        if($good_id<=0){
            $this->error(lang('operation not valid'));
        }
        $goods = Db::name('goods')->alias("g")->join("__GOODS_CATE__ gc","gc.gid = g.id","LEFT")
                    ->join("__CATEGORY__ c","gc.cid = c.id","LEFT") 
                    ->where(["g.id"=>$good_id])->field("g.*,c.cate_name,gc.cid")->find();
        $this->assign("goods",$goods);
        return $this->view->fetch();
    }
    
    public function del(){
        $order_id = input("id",0,"intval");
        if($order_id<=0){
            $this->error(lang('operation not valid'));
        }
        $order = Db::name('goods_order')->where(['id'=>$order_id])->find();
        if($order){
            if($order["state_trade"]==1 || $order["state_trade"]==2){
                $res = Db::name('goods_order')->where(['id'=>$order_id])->setfield("state_trade",-1);
                if($res){
                    //如果为已支付则退还费用
                    if($order["state_pay"]==2){
                        $param = [
                            'uid'     =>session('hid'),
                            'isadd'   =>true,
                            'fee'     =>$order["total_fee"],
                            'title'   => "取消订单，退还已支付费用，共计({$order["total_fee"]}元)",
                            'order_id'=>$order['id'],
                            'content' =>"用户[uid:".session('hid')."]取消订单，退还已支付费用，共计({$order["total_fee"]}元)"
                            ];
                        $res = add_member_log($param);
                    }
                    $this->success("订单取消成功！",url("home/center/orderlist"));
                }else{
                    $this->error("抱歉，操作失败！");
                }
            }else{
                $this->error("抱歉，订单当前状态不允许取消！");
            }
        }else{
            $this->error("抱歉，订单信息缺失！");
        }
    }
}
